'use strict';

const NodeRSA = require('node-rsa');
const fs = require('fs');
const path = require('path');


// 获取config/kes文件夹的绝对路径
const targetUrl = path.resolve(__dirname, './../../config/keys');

class KeyContrulor {
  constructor() {
    // 生成钥匙的方法
    this.createKeys = async () => {
      // 生成一个秘钥//证书
      const key = new NodeRSA({ b: 512 });
      // 获取公钥
      const publicKey = key.exportKey('public');
      // 获取私钥
      const privateKey = key.exportKey('private');
      // 存储我们生成的公钥
      await fs.promises.writeFile(targetUrl + '/publicKey.key', publicKey, {
        encoding: 'utf-8',
      });
      await fs.promises.writeFile(targetUrl + '/privateKey.key', privateKey, {
        encoding: 'utf-8',
      });
      return {
        publicKey,
        privateKey,
      };
    };
    // 获取钥匙的方法
    this.getKeys = async () => {
      const dirs = await fs.promises.readdir(targetUrl);
      console.log('dirs', dirs);
      if (dirs.length === 0) {
        // 服务端本地没有钥匙
        const res = await this.createKeys();
        return res;
      }
      // 服务端本地有钥匙
      const res = await fs.promises.readFile(targetUrl + '/publicKey.key', {
        encoding: 'utf-8',
      });
      return res;


    };
  }


}


module.exports = new KeyContrulor();
